import { Component, ViewChild } from '@angular/core';
import {
  DataTableComponent,
  DialogService,
  DrawerService,
  IDrawerOpenResult,
  TableWidthConfig,
} from 'ng-devui';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { LogComponent } from 'src/app/@shared/components/log/log.component';
import { environment } from 'src/environments/environment';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { Router } from '@angular/router';
import { PurchaseService } from 'src/app/@core/services/purchase/purchase.service';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { PurchaseInspectionOrder } from 'src/app/@core/data/purchase';
import { PurchaseInspectionDetailsComponent } from './purchase-inspection-details/purchase-inspection-details.component';

@Component({
  selector: 'app-purchase-inspection',
  templateUrl: './purchase-inspection.component.html',
  styleUrls: ['./purchase-inspection.component.scss'],
})
export class PurchaseInspectionComponent {
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20,
  };
  results: IDrawerOpenResult;
  pageSizeOptions = [10, 20, 30, 50, 100];
  tableData: PurchaseInspectionOrder[] = [
    {
      purchaseInspectionOrderId: 0, //采购到货单ID
      purchaseInspectionOrderNum: '', //采购到货单号
      partNum: '', //物料编号
      partUOM: '', //物料单位
      partName: '', //物料名称
      description: '', //物料描述
      partType: '', //规格型号
      image: '', //图片
      status: '', //状态
      supplyShortName: '', //供应商
      supplyChineseName: '', //供应商全称
      inspectionQuantity: 0, //检验数量
      inspectionDate: '', //检验日期
      qualifiedQuantity: 0, //合格数量
      unqualifiedQuantity: 0, //不合格数量
      pioPartId: 0, //采购订单物料ID
      warehouseId: 0, //仓库ID
      warehouseName: '', //仓库名称
      warehouseNum: '', //仓库编号
      positionId: 0, //库位ID
      positionName: '', //库位名称
      positionNum: '', //库位编号
      note: '', //备注
      purchaseOrderPartId: 0, //采购订单物料ID
      purchaseArrivalOrderNum: '', //采购到货单号
      purchaseArrivalOrderPartId: 0, //采购到货单物料ID
      pioPurchaseArrivalOrderId: 0, //采购到货单ID
    },
  ];
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '操作',
        fieldType: 'text',
        fixedLeft: '80px',
      },
      {
        field: 'name',
        header: '采购质检单',
        fieldType: 'text',
        fixedLeft: '350px',
      },
      {
        field: '物料名称',
        header: '物料名称',
        fieldType: 'text',
      },
      {
        field: '物料编码',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: '检验数量',
        header: '检验数量',
        fieldType: 'text',
      },
      {
        field: '合格数量',
        header: '合格数量',
        fieldType: 'text',
      },
      {
        field: '不合格数量',
        header: '不合格数量',
        fieldType: 'text',
      },
      {
        field: '图片',
        header: '图片',
        fieldType: 'text',
      },
      {
        field: '规格型号',
        header: '规格型号',
        fieldType: 'text',
      },
      {
        field: '物料描述',
        header: '物料描述',
        fieldType: 'text',
      },
      {
        field: '物料单位',
        header: '物料单位',
        fieldType: 'text',
      },
      {
        field: '供应商',
        header: '供应商',
        fieldType: 'text',
      },
      {
        field: '供应商全称',
        header: '供应商全称',
        fieldType: 'text',
      },


      {
        field: '仓库名称',
        header: '仓库名称',
        fieldType: 'text',
      },
      {
        field: '库位名称',
        header: '库位名称',
        fieldType: 'text',
      },
      {
        field: '采购到货单号',
        header: '采购到货单号',
        fieldType: 'text',
      },
      {
        field: '检验日期',
        header: '检验日期',
        fieldType: 'text',
      },
      {
        field: '二维码',
        header: '二维码',
        fieldType: 'text',
      },
      {
        field: '备注',
        header: '备注',
        fieldType: 'text',
      },
      {
        field: '日志',
        header: '日志',
        fieldType: 'text',
      },
      // {
      //   field: '状态',
      //   header: '状态',
      //   fieldType: 'text',
      //   fixedRight: '0px',
      // },
    ],
  }; //表格数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '80px',
    },
    {
      field: '操作',
      width: '270px',
    },
    {
      field: '采购质检单',
      width: '200px',
    },
    {
      field: '物料名称',
      width: '150px',
    },
    {
      field: '物料编码',
      width: '150px',
    },
    {
      field: '检验数量',
      width: '150px',
    },
    {
      field: '合格数量',
      width: '150px',
    },
    {
      field: '不合格数量',
      width: '150px',
    },
    {
      field: '图片',
      width: '170px',
    },
    {
      field: '规格型号',
      width: '150px',
    },
    {
      field: '物料描述',
      width: '150px',
    },
    {
      field: '物料单位',
      width: '150px',
    },
    {
      field: '供应商',
      width: '170px',
    },
    {
      field: '供应商全称',
      width: '170px',
    },


    {
      field: '仓库名称',
      width: '150px',
    },
    {
      field: '库位名称',
      width: '150px',
    },
    {
      field: '采购到货单号',
      width: '200px',
    },
    {
      field: '检验日期',
      width: '200px',
    },
    {
      field: '二维码',
      width: '150px',
    },
    {
      field: '备注',
      width: '150px',
    },
    {
      field: '日志',
      width: '150px',
    },
    // {
    //   field: '状态',
    //   width: '150px',
    // },
  ]; //表格宽度配置
  msgs: { severity: any; summary: any; content: any }[];
  fifter = {
    PageSize: 20,
    PageNumber: 1,
    StartTime: '',
    EndTime: '',
    PurchaseInspectionOrderNum: '',
    Part: '',
    Status: '',
  };
  Customer: any = [];
  creatTime: any = [];
  splitBarSize = '0px';
  partDetailHeight = '100%';
  @ViewChild(DataTableComponent, { static: true })
  datatable: DataTableComponent;
  checkedIds: any = [];
  partDetail: any = [];
  selectedRowIndex: any;
  date = [];
  // statusOptions = ['未开始审核', '审核中', '审核通过'];
  constructor(
    private SharedMethodService: SharedMethodService,
    private Router: Router,
    private DialogService: DialogService,
    private PurchaseService: PurchaseService,
    private dialogService: DialogService,
    private drawerService: DrawerService,
    private ReviewRolesService: ReviewRolesService
  ) {}
  ngOnInit(): void {
    this.filter();
  }
  filter() {
    this.PurchaseService.GetPurchaseInspectionOrder(this.fifter).subscribe(
      (data: any) => {
        this.tableData = data.items;
      },
      (error: any) => {
        this.showToast('error', '失败', error.error || '服务器连接失败');
      }
    );
  }
  filter2() {
    this.fifter.PageNumber = 1;
    this.PurchaseService.GetPurchaseInspectionOrder(this.fifter).subscribe(
      (data: any) => {
        this.tableData = data.items;
      },
      (error: any) => {
        this.showToast('error', '失败', error.error || '服务器连接失败');
      }
    );
  }
  reset() {
    this.fifter = {
      PageSize: 20,
      PageNumber: 1,
      StartTime: '',
      EndTime: '',
      PurchaseInspectionOrderNum: '',
      Part: '',
      Status: '',
    };
    this.date = [];
    this.filter();
  }
  onRowCheckChange(
    checked: any,
    rowIndex: any,
    nestedIndex: any,
    rowItem: { $checked: any; $halfChecked: boolean }
  ) {
    this.SharedMethodService.onRowCheckChange(
      checked,
      rowIndex,
      nestedIndex,
      rowItem,
      this.datatable
    );
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'purchaseArrivalOrderId'
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
    this.SharedMethodService.getCheckedRows(
      this.datatable,
      'purchaseArrivalOrderNum'
    ).subscribe((data: any) => {
      this.checkedCodes = data;
    });
  } //获取选中行
  CheckedRows = [];
  getCheckedRowsData() {
    this.SharedMethodService.getCheckedRowsData(this.datatable).subscribe(
      (data: any) => {
        this.CheckedRows = data;
      }
    );
  }
  cleared() {
    this.SharedMethodService.cleared(
      this.checkedIds,
      this.tableData,
      this.datatable
    ).subscribe((data: any) => {
      this.checkedIds = data;
    });
  } //清空选中行
  pageIndexChange($event: any) {
    this.filter();
  } //切换页码
  pageSizeChange($event: any) {
    this.filter();
  } //改变每页显示数量
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  deleteIsArrivalInCheckedIds() {
    const existsIsArrivalTrue = this.tableData.some(
      (item) =>
        this.checkedIds.includes(item.purchaseInspectionOrderId) &&
        item.status === '审核通过'
    );
    return existsIsArrivalTrue;
  }
  allLog() {
    this.PurchaseService.GetAllPurchaseInspectionOrderLogs(1, 9999).subscribe(
      (data: any) => {
        const logData = data.items;
        const columns = [
          {
            field: '采购质检单号',
            header: '采购质检单号',
            fieldType: 'text',
          },
          {
            field: 'content',
            header: '日志内容',
            fieldType: 'text',
          },
          {
            field: '执行人',
            header: '执行人',
            fieldType: 'text',
          },
          {
            field: '执行时间',
            header: '执行时间',
            fieldType: 'text',
          },
        ];
        this.results = this.drawerService.open({
          drawerContentComponent: LogComponent,
          width: '40%',
          data: { data: logData, columns: columns },
          zIndex: 1000,
          isCover: false,
          fullScreen: true,
          backdropCloseable: true,
          escKeyCloseable: true,
          position: 'right',
          resizable: true,
          onClose: () => {},
        });
      }
    );
  }
  GetLogsById(id: any) {
    this.PurchaseService.GetLogsByPurchaseInspectionOrderId(
      id,
      1,
      9999
    ).subscribe((data: any) => {
      const logData = data.items;
      const columns = [
        {
          field: '采购质检单号',
          header: '采购质检单号',
          fieldType: 'text',
        },
        {
          field: 'content',
          header: '日志内容',
          fieldType: 'text',
        },
        {
          field: '执行人',
          header: '执行人',
          fieldType: 'text',
        },
        {
          field: '执行时间',
          header: '执行时间',
          fieldType: 'text',
        },
      ];
      this.results = this.drawerService.open({
        drawerContentComponent: LogComponent,
        width: '40%',
        data: { data: logData, columns: columns },
        zIndex: 1000,
        isCover: false,
        fullScreen: true,
        backdropCloseable: true,
        escKeyCloseable: true,
        position: 'right',
        resizable: true,
        onClose: () => {},
      });
    });
  }
  checkCustomerIDs(customerRows: any) {
    // 如果数组长度为1或为空，直接返回true
    if (customerRows.length <= 1) {
      return true;
    }
    // 获取第一个元素的customerID
    const firstCustomerID = customerRows[0].customerID;
    // 检查数组中每个元素的customerID是否都与第一个元素的customerID相同
    return customerRows.every(
      (row: { customerID: any }) => row.customerID === firstCustomerID
    );
  }
  downloadTemplate() {
    this.PurchaseService.exportPurchaseRequirementToExcelModel().subscribe(
      (data: any) => {
        const blob = new Blob([data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', '采购订单模版.xlsx');
        a.click();
        URL.revokeObjectURL(objectUrl);
      }
    );
  }
  file: any;
  import(event: any) {
    this.file = event.target.files[0];
    this.PurchaseService.importPurchaseRequirementFromExcel(
      this.file
    ).subscribe((data: any) => {
      const blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '采购订单.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
      this.filter();
    });
  }
  @ViewChild('fileInput2') fileInput2: any;
  onButtonClick() {
    this.fileInput2.nativeElement.click();
  }
  download() {
    this.PurchaseService.exportPurchaseRequirementToExcel().subscribe(
      (data: any) => {
        const blob = new Blob([data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });
        const objectUrl = URL.createObjectURL(blob);
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', '采购订单.xlsx');
        a.click();
        URL.revokeObjectURL(objectUrl);
      }
    );
  }
  fujian(rowitem: any, dialogtype?: string) {
    const results = this.dialogService.open({
      title: '附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '销售附件',
        urls: rowitem.files,
        type: '查看',
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  showDetail(data: any, rowIndex: any) {
    this.selectedRowIndex = rowIndex;
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + url);
    return urls;
  }
  dateChange() {
    this.fifter.StartTime = this.date[0]
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '/');
    this.fifter.EndTime = this.date[1]
      .toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
      })
      .replace(/\//g, '/');
  }
  checkedCodes = [];
  clickCode(rowItem: any, type: string, dialogtype?: string) {
    {
      let data = {
        data: rowItem,
        type: type,
        disPlay: false,
      };
      const results = this.DialogService.open({
        id: 'custom',
        width: '80vw',
        maxHeight: '90vh',
        backdropCloseable: true,
        content: PurchaseInspectionDetailsComponent,
        dialogtype: dialogtype,
        data: data,
        onClose: () => {},
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              if (
                results.modalContentInstance.tempData.data.qualifiedQuantity !==
                null
              ) {
                if (
                  results.modalContentInstance.tempData.data.qualifiedQuantity +
                    results.modalContentInstance.tempData.data
                      .unqualifiedQuantity ==
                  results.modalContentInstance.tempData.data.inspectionQuantity
                ) {
                  this.PurchaseService.ChangePurchaseInspectionOrder(
                    rowItem.purchaseInspectionOrderId,
                    results.modalContentInstance.tempData.data.qualifiedQuantity
                  ).subscribe(
                    (res) => {
                      this.showToast('success', '成功', '检验成功');
                      this.filter();
                      results.modalInstance.hide();
                    },
                    (error) => {
                      this.showToast(
                        'error',
                        '错误',
                        error.error || '服务器连接失败'
                      );
                    }
                  );
                } else {
                  this.showToast('error', '错误', '未检验完成');
                }
              } else if (
                results.modalContentInstance.tempData.data.qualifiedQuantity ==
                null
              ) {
                this.showToast('error', '错误', '请输入数量');
              }
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '暂存',
            handler: ($event: Event) => {
              if (
                results.modalContentInstance.tempData.data.qualifiedQuantity !==
                null
              ) {
                this.PurchaseService.CreateOrUpdateInspectionOrderTemporary({
                  inspectionOrderTemporaryId: null,
                  inspectionOrderId:
                    results.modalContentInstance.tempData.data
                      .purchaseInspectionOrderId,
                  inspectionOrderNum:
                    results.modalContentInstance.tempData.data
                      .purchaseInspectionOrderNum,
                  qualifiedQuantity:
                    results.modalContentInstance.tempData.data
                      .qualifiedQuantity,
                  unqualifiedQuantity:
                    results.modalContentInstance.tempData.data
                      .unqualifiedQuantity,
                }).subscribe(
                  (res) => {
                    this.showToast('success', '成功', '暂存成功');
                    this.filter();
                    results.modalInstance.hide();
                  },
                  (error) => {
                    this.showToast(
                      'error',
                      '错误',
                      error.error || '服务器连接失败'
                    );
                  }
                );
              } else if (
                results.modalContentInstance.tempData.data.qualifiedQuantity ==
                null
              ) {
                this.showToast('error', '错误', '请输入数量');
              }
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }
  clickCode2(rowItem: any, type: string, dialogtype?: string) {
    {
      let data = {
        data: rowItem,
        type: type,
        disPlay: false,
      };
      const results = this.DialogService.open({
        id: 'custom',
        width: '80vw',
        maxHeight: '90vh',
        backdropCloseable: true,
        content: PurchaseInspectionDetailsComponent,
        dialogtype: dialogtype,
        data: data,
        onClose: () => {},
        buttons: [
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '关闭',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }
  getImagesArray2(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + '/' + url);
    return urls;
  }
}
